<template>
  <el-dialog
    v-model="drawerVisible"
    @close="close"
    :destroy-on-close="true"
    size="450px"
    width="750px"
    :title="`${drawerProps.title}菜单`"
  >
    <el-form
      class="form"
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :inline="true"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="路由Name" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="唯一英文字符串" clearable></el-input>
      </el-form-item>
      <el-form-item label="路由Path" prop="path">
        <el-input v-model="drawerProps.row!.path" placeholder="请填写路由Path" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否重定向" prop="redirect">
        <el-input v-model="drawerProps.row!.redirect" placeholder="请填写重定向路由Path" clearable></el-input>
      </el-form-item>
      <el-form-item label="显示/隐藏" prop="status">
        <el-select v-model="drawerProps.row!.status" class="m-2" placeholder="">
          <el-option label="隐藏" :value="0" /><el-option label="显示" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="父节点ID" prop="parentId">
        <el-cascader
          :disabled="disabledParentId"
          v-model="drawerProps.row!.parentId"
          :show-all-levels="false"
          :options="routerList"
          :props="{
            checkStrictly: true,
            emitPath: false,
            value: 'id',
            label: 'title',
            children: 'childList'
          }"
          clearable
        />
      </el-form-item>
      <el-form-item label="文件路径" prop="component">
        <el-input v-model="drawerProps.row!.component" placeholder="页面:view/xx/xx.vue" clearable></el-input>
      </el-form-item>
      <el-form-item label="展示名称" prop="title">
        <el-input v-model="drawerProps.row!.title" clearable></el-input>
      </el-form-item>
      <el-form-item label="图标" prop="icon">
        <icon v-model="drawerProps.row!.icon" style="width: 100%" />
        <!-- <el-input v-model="drawerProps.row!.icon" clearable></el-input> -->
      </el-form-item>
      <el-form-item label="排序标记" prop="sort">
        <el-input v-model="drawerProps.row!.sort" type="number" clearable></el-input>
      </el-form-item>
      <el-form-item label="KeepAlive" prop="isKeepAlive">
        <el-select v-model="drawerProps.row!.isKeepAlive" class="m-2" placeholder="">
          <el-option label="否" :value="0" /><el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="level" prop="level">
        <el-input v-model="drawerProps.row!.level" type="number" clearable></el-input>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts" name="MenuDrawer">
import { ref, reactive } from "vue";
// import { genderType } from "@/utils/dict";
import { ElMessage, FormInstance } from "element-plus";
import { System } from "@/api/interface";
import icon from "./Icon.vue";

const rules = reactive({
  name: [{ required: true, message: "请填写路由name" }],
  path: [{ required: true, message: "请填写路由path" }],
  component: [{ required: true, message: "请填写文件路径" }],
  title: [{ required: true, message: "请填写菜单展示名称" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<System.ResMenuList>;
  api?: (params: any) => Promise<any>;
  getRouterList?: (params?: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

let disabledParentId = ref(true);
let routerList = ref<any[]>([]);
// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  let copyParams = JSON.parse(JSON.stringify(params));
  drawerProps.value = params;
  drawerVisible.value = true;
  if (params.title == "编辑") {
    disabledParentId.value = false;
    let { data } = await params.getRouterList!({ pageNum: 1, pageSize: 1000 });
    routerList.value = [{ title: "根目录", id: 0 }, ...data.list];
    drawerProps.value.row.parentId = getNodeById(params.row.parentId!, routerList.value).id || 0;
  } else if (params.title === "新增") {
    disabledParentId.value = true;
    routerList.value = [{ title: "根目录", id: 0 }];
    drawerProps.value.row.parentId = 0;
    drawerProps.value.row.parentIds = "0,";
    drawerProps.value.row.level = 1;
  } else {
    disabledParentId.value = true;
    routerList.value = [
      { title: "根目录", id: 0 },
      { title: params.row.title!, id: params.row.id! }
    ];
    drawerProps.value.row = {};
    drawerProps.value.row.parentId = copyParams.row.id || 0;
    drawerProps.value.row.parentIds = copyParams.row.parentIds + copyParams.row.id + ",";
    drawerProps.value.row.level = copyParams.row.level + 1;
  }
};
const getNodeById = (id: number | string, nodes: any[]): any => {
  for (const node of nodes) {
    if (node.id == id) {
      return node; // 找到匹配的节点，返回节点对象
    }
    if (node.childList) {
      const result = getNodeById(id, node.childList);
      if (result) {
        return result; // 在子节点中找到了匹配的节点，返回节点对象
      }
    }
  }
  return null; // 未找到匹配的节点，返回 null
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});

const close = () => {
  routerList.value = [];
};
</script>
<style lang="scss" scoped>
.form {
  :deep(.el-input) {
    --el-input-width: 220px;
  }
}
</style>
